﻿// (c) Copyright 2013 Mike Riedel.
// This source is subject to the Microsoft Public License (Ms-PL).
// All other rights reserved.

namespace System.Diagnostics
{

   /// <summary>
   /// A base-bones version of the Stopwatch class that was dropped as of Silverlight 4.
   /// This doesn't have the high resolution of the one in the full .NET Framework but it's
   /// better than nothing.
   /// </summary>
   public class Stopwatch
   {
      long start;
      long previousElapsed;

      /// <summary>
      /// Starts or resumes measuring elapsed time.
      /// </summary>
      public void Start()
      {
         start = DateTime.Now.Ticks;
         IsRunning = true;
      }

      /// <summary>
      /// Stops measuring elapsed time.
      /// </summary>
      public void Stop()
      {
         previousElapsed += DateTime.Now.Ticks - start;
         IsRunning = false;
      }

      long CurrentElapsed
      {
         get { return (IsRunning ? DateTime.Now.Ticks - start : 0); }
      }

      /// <summary>
      /// Gets the total elapsed time in ticks.
      /// </summary>
      public long ElapsedTicks
      {
         get { return previousElapsed + CurrentElapsed; }
      }

      /// <summary>
      /// Gets the total elapsed time.
      /// </summary>
      public TimeSpan Elapsed
      {
         get { return new TimeSpan(ElapsedTicks); }
      }

      /// <summary>
      /// Gets the total elapsed time in milliseconds.
      /// </summary>
      public double ElapsedMilliseconds
      {
         get { return Elapsed.TotalMilliseconds; }
      }

      /// <summary>
      /// Stops measuring elapsed time and resets elapsed time to 0.
      /// </summary>
      public void Reset()
      {
         Stop();
         previousElapsed = 0;
         start = 0;
      }

      /// <summary>
      /// Stops measuring elapsed time, resets elapsed time to 0, and then starts measuring elapsed time.
      /// </summary>
      public void Restart()
      {
         Reset();
         Start();
      }

      /// <summary>
      /// Indicates whether elapsed time is being measured.
      /// </summary>
      public bool IsRunning { get; private set; }

      /// <summary>
      /// Indicates whether high-resolution is available.
      /// Always false for Silverlight.
      /// </summary>
      public bool IsHighResolution
      {
         get { return false; }
      }

      /// <summary>
      /// Creates a new instance and starts measuring elapsed time.
      /// </summary>
      /// <returns></returns>
      public static Stopwatch StartNew()
      {
         var stopwatch = new Stopwatch();
         stopwatch.Start();
         return stopwatch;
      }
   }
}
